$(function(){
	ProductTypeIndex()//显示商品类型
	ProductIndex()//显示商品列表
	$('.skinList').children().not(":first").map(function(i,v){
		$(this).css({
			"background-image":"url('img/back"+i+".png')",
			"background-size":"100%"+" "+"100%"
		})
		$('.skinListDiv').eq(0).find("i").show()
	})
	$('.skinBox-after').click(function(){
		if($('.skinBox').offset().top==0){
			$('.skinBox').animate({
				top:"-40%",
				/*opacity:"0"*/
			},400)
			$(this).children().attr("class","fa fa-angle-down")
			$('.bg-mask-div').hide()
		}
		else{
			$('.skinBox').animate({
				top:"0",
				opacity:"1"
			},400)
			$(this).children().attr("class","fa fa-angle-up")
			$('.bg-mask-div').show()
			$('.bg-mask-div').click(function(){
				$('.skinBox').animate({
					top:"-40%",
					/*opacity:"0"*/
				},1000)
				$('.bg-mask-div').hide()
			})
		}
	})
	$('.skinListDiv').click(function(){
		var link = $(this).css("backgroundImage")
		var _index = $(this).index()
		console.log(_index)
		$(this).children('i').show()
		$(this).siblings().children('i').hide()
		$(this).siblings(".colorPrintor").find("i").hide()
		$("body").attr("style","transition:all 2s")
		if(_index==1){
			$('head link').eq(4).attr("href","css/index.css")
		}
		else if(_index==2){
			$('head link').eq(4).attr("href","css/index2.css")
		}
		else if(_index==3){
			$('head link').eq(4).attr("href","css/index3.css")
		}
	})
	$('.colorPrintor ul li').click(function(){
		var _index = $(this).index()
		$('head link').eq(4).attr("href","css/index4.css")
		$(this).children('i').show()
		$(this).siblings().children('i').hide()
		$(this).parents(".colorPrintor").siblings(".skinListDiv").find("i").hide()
		var nowBackground = $('.colorPrintor ul li').eq(_index).find('span').css("background-color")
		$('body').css("background",nowBackground)
	})
	/*background: url('../img/back.png');
    background: url('../img/back2.png');
    background: url('../img/back3.png');*/
})
//显示商品类型
function ProductTypeIndex(){
	$.ajax({
		url: "getProductType.action",
		type:"post",
		dataType:"json",
		success:function(result){
			var time = 0;
			for(var i=0;i<result.length;i++){
				$('.product-type-list').find("ul").append("<li><span id='"+result[i].id+"' >"+result[i].name+"</span></li>")
			}
			$(".product-type-before").children().off("click").on("click",function(){
				var moveXpage = $(".list-tmp-ul li").width()*6
				var l = $(".list-tmp-ul li").width()
				var maxLeft = $(".list-tmp-ul li").length*l
				var maxTime = Math.floor(maxLeft/moveXpage)
				console.log(maxTime)
				if(this.className=="produxtTypeBefore"&&time<maxTime){
					var nowLeft = parseInt($(".list-tmp-ul").css("left"))
					time++
					$(".list-tmp-ul").animate({
						left: nowLeft-moveXpage+"px"
					},1000,'easeOutQuint',function(){
						if(time==maxTime){
							$(".product-type-before").children().eq(0).fadeOut(200).siblings().css("display","table")
						}
					})
				}
				else if(this.className=="produxtTypeAfter"&&time>0){
					var nowLeft = parseInt($(".list-tmp-ul").css("left"))
					time--
					$(".list-tmp-ul").animate({
						left: nowLeft+moveXpage+"px"
					},1000,'easeOutQuint',function(){
						if(time==0){
							$(".product-type-before").children().eq(1).fadeOut(200).siblings().fadeIn(200)
						}
					})
				}
			})
		},
		error:function(){
			
		}
	})
}
//商品类型下所有的商品
function getProductByType(a){
	console.log(a)
	/*console.log(a.product.producttype.name)*/
	$('.product-type-list ul li').not(":first").off("click").on("click",function(){
		$(this).find("span").addClass("pressDown").parent().siblings().children().removeClass("pressDown")
		var tmp = [];
		/*$('.product-tree h4').text($(this).find("span").text())*/
		for(var i=0;i<a.length;i++){
			if(a[i].product.producttype.name==$(this).find("span").text()){
//				var tmp = [];
				tmp.push(a[i])
			}
		}
		console.log(tmp)
		imageViewProduct(tmp)
		indexProductTable(tmp)
	})
	$('.product-type-list ul li :first').off("click").on("click",function(){
//		console.log($(this)addClass("pressDown"))
		$(this).addClass("pressDown")
		$('.product-type-list ul li').not(":first").find("span").removeClass("pressDown")
		indexProductTable(a)
		imageViewProduct(a)
		/*$('.product-tree h4').text("所有商品")*/
	})
}
/*function getProductByType(a){
	var size = 7;
	var type = 20;
	var _length = Math.ceil(type/size);
	var name = "nihao"
	var li = "<li>"+name+"</li>"
	var prev = "<li><</li>"
	var next = "<li>></li>"
	 for(var i=0;i<_length-1;i++){
		$('.product-type-list').append("<ul style='display:none' ></ul>")
	} 
	if(type>size){
		 $('.product-type-list>ul').append("<li><span>&laquo;</span></li>") 
		for(var i=0;i<type;i++){
			$('.product-type-list').find("ul").append("<li><span>"+name+i+"</span></li>")
		}
		 $('.product-type-list').find("ul").append("<li><span>&raquo;</span></li>") 
	}
	else{
		for(var i=0;i<_length;i++){
			$('.product-type-list').find("ul").append("<li><span>"+name+i+"</span></li>")
		}
	}
	var time = 0;
	$(".product-type-before").children().off("click").on("click",function(){
		var moveXpage = $(".list-tmp-ul li").width()*6
		var l = $(".list-tmp-ul li").width()
		var maxLeft = $(".list-tmp-ul li").length*l
		var maxTime = Math.floor(maxLeft/moveXpage)
		console.log(maxTime)
		if(this.className=="produxtTypeBefore"&&time<maxTime){
			var nowLeft = parseInt($(".list-tmp-ul").css("left"))
			time++
			$(".list-tmp-ul").animate({
				left: nowLeft-moveXpage+"px"
			},1500,'easeOutQuint',function(){
				if(time==maxTime){
					$(".product-type-before").children().eq(0).fadeOut(200).siblings().css("display","table")
				}
			})
		}
		else if(this.className=="produxtTypeAfter"&&time>0){
			var nowLeft = parseInt($(".list-tmp-ul").css("left"))
			time--
			$(".list-tmp-ul").animate({
				left: nowLeft+moveXpage+"px"
			},1500,'easeOutQuint',function(){
				if(time==0){
					$(".product-type-before").children().eq(1).fadeOut(200).siblings().fadeIn(200)
				}
			})
		}
	})
}
*/
//显示商品列表
function ProductIndex(){
	$.ajax({
		url: "getProduct.action",
		type:"post",
		dataType:"json",
		success:function(result){
			/*console.log(result)*/
			imageViewProduct(result)
			indexProductTable(result)
			getProductByType(result)
		},
		error:function(){
			
		}
	})
}
//商品视图控制
$(function(){
	$('.view-control li').click(function(){
		var _index = $(this).index()
		$('.product-list-wrapper').children(".controlled").eq(_index).show().siblings().hide()
		$(this).addClass("press").siblings("li").removeClass("press")
	})
})
function indexProductTable(data){
//	console.log(data)
	$('#productTable').DataTable({
		destroy: true,
		"bAutoWidth":false,
		responsive: true,
		"bStateSave": true,
		data: data,
		"columnDefs":[
		    {
				"targets":[5],
				"searchable":false
			},
			{
				"targets":[3],
				"searchable":false
			},
		],
		//使用对象数组，一定要配置columns，告诉 DataTables 每列对应的属性
		columns: [{
				data: 'product.productName'
			},
			{
				data: 'product.productNo'
			},
			{
				data: 'product.producttype.name'
			},
			{
				data: 'spec'
			},
			{
				data: 'product.remark'
			},
			{
				data: 'product.remark'
			}
		],
		language: {
	        "sProcessing": "处理中...",
	        "sLengthMenu": "显示 _MENU_ 项结果",
	        "sZeroRecords": "没有匹配结果",
	        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
	        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
	        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
	        "sInfoPostFix": "",
	        "sSearchPlaceholder":"输入名称或编码或类型",	
	        "sSearch": "搜索:",
	        "sUrl": "",
	        "sEmptyTable": "暂无产品",
	        "sLoadingRecords": "载入中...",
	        "sInfoThousands": ",",
	        "oPaginate": {
	            "sFirst": "首页",
	            "sPrevious": "上一页",
	            "sNext": "下一页",
	            "sLast": "末页"
	        },
	        "oAria": {
	            "sSortAscending": ": 以升序排列此列",
	            "sSortDescending": ": 以降序排列此列"
	        }
	    },
	    "fnCreatedRow": function( nRow, aData, iDataIndex ){ 
	    	$('td:eq(5)',nRow).html("<button class='btn btn-primary'>下单</button>")
	    	$('td:eq(3)',nRow).html("<select class='form-control'></select>")
	    	for(var i=0;i<aData.spec.length;i++){
		    		$('td:eq(3) select',nRow).append("<option value='"+aData.spec[i][2]+"'>"+aData.spec[i][3]+"</option>")
	    	}
//	    	$('td:eq(3)',nRow).html("<select class='form-control'><option value='"+aData.spec[0][2]+"'>大杯</option><option value='"+aData.spec[1][2]+"'>中杯</option><option value='"+aData.spec[2][2]+"'>小杯</option></select>")
		    $('td:eq(5) button',nRow).click(function(){
				var array = $('.product-list').find('li').map(function(index){
					return $(this).eq(0).find('.product-top-description h4').text()
					+$(this).eq(0).find('.product-top-description span').text()
				}).get()
				var name = aData.product.productName
				var spec = $('td:eq(3) select',nRow).find("option:selected").text()
				var tmp = name+spec
//				console.log(tmp)
//				if($('.product-list').find('li').length==0||array.indexOf(tmp)==-1){
					var price = $('td:eq(3) select',nRow).val()
//					var spec = $('td:eq(3) select',nRow).find("option:selected").text()
					var product = "<div class='product-top-description'><h4>"+name+"</h4><span class='product-middle-spec'>"+spec+"</span><label>温度<select class='tmp'><option>热</option><option>冷</option></select></label><label>甜度<select class='swt'><option>30%</option><option>50%</option><option>70%</option><option>100%</option></select></label></div><div class='product-down-price'><div class='product-num-choose'><span class='minus' >－</span><span class='product-num-span' ><input class='product-num' value='1' tyep='text'/></span><span class='add'>＋</span></div><div class='product-num-price'><span><i></i>"+price+"</span></div></div><div class='product-right-delete'><i class='fa fa-trash-o' aria-hidden='true'></i></div>"
					$('.product-list').find('ul').append("<li proNo="+aData.product.productNo+">"+product+"</li>")
					addRedDotsTips(name,"add1",1)
//				}
//				else{
//					var location = array.indexOf(tmp)
////					var location = array.indexOf(spec)
//					var tmp = Number($('.product-list').find('li').eq(location).find("input").val())
//					if(tmp<30){
//						$('.product-list').find('li').eq(location).find("input").val(tmp+1)
//					}
//					else{
//						alert('单笔最多30杯!!!')
//					}
//				}
				productModule.productNum()
				productModule.TotalProduct()
				productModule.deleteProduct()
			})
		},
		"fnRowCallback": function(nRow, aaData, iDisplayIndex, iDisplayIndexFull) {
//			alert("1'")
		},
	})
}
//结账
function createSale(){
	if($('.product-list ul li').length>0){
		var array= $('.product-list ul li').map(function(){
			return {
				"itemId":$(this).attr("prono"),
				"quantity":$(this).find('.product-num').val(),
				"price":$(this).find(".product-num-price").children().text(),
				"spec":$(this).find('.product-middle-spec').text(),
				"sweetness":$('.swt').val(),
				"temperature":$('.tmp').val()
			}
		})
		var arr = JSON.stringify(array)
		console.log(array)
		$.ajax({
			url: "createSale.action",
			type:"post",
			dataType:"json",
			data:{
				"saleorder.total":$('.footer-btn li').eq(2).find("i").eq(1).text(),
				"staff.staffNo":"2",
				"inputdata":arr,
				"inputSize":array.length
			},
			success:function(result){
				paymentDecision(result[0],array)
				receipt()
				$('#paymentType').modal('show')
			},
			error:function(){
				
			}
		})
	}
	else{
		alert("待下单列表为空")
	}
}
function getAllOrder(){
	$.ajax({
		url: "getAllOrder.action",
		type:"post",
		dataType:"json",
		success:function(result){
//			console.log(result)
			oderTable(result)
		},
		error:function(){
			
		}
	})
}
function oderTable(data){
//	console.log(data)
	$('#oderTable').DataTable({
		destroy: true,
		"bAutoWidth":false,
		responsive: true,
		"bStateSave": true,
		data: data,
		//使用对象数组，一定要配置columns，告诉 DataTables 每列对应的属性
		columns: [{
				data: 'saleOrderNo'
			},
			{
				data: 'saleDateTime'
			},
			{
				data: 'total'
			},
			{
				data: 'staff.name'
			},
			{
				data: 'paymentStatus'
			},
			{
				data: 'id'
			}
		],
		language: {
	        "sProcessing": "处理中...",
	        "sLengthMenu": "显示 _MENU_ 项结果",
	        "sZeroRecords": "没有匹配结果",
	        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
	        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
	        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
	        "sInfoPostFix": "",
	        "sSearch": "搜索:",
	        "sUrl": "",
	        "sEmptyTable": "表中数据为空",
	        "sLoadingRecords": "载入中...",
	        "sInfoThousands": ",",
	        "oPaginate": {
	            "sFirst": "首页",
	            "sPrevious": "上页",
	            "sNext": "下页",
	            "sLast": "末页"
	        },
	        "oAria": {
	            "sSortAscending": ": 以升序排列此列",
	            "sSortDescending": ": 以降序排列此列"
	        }
	    },
	    "fnCreatedRow": function( nRow, aData, iDataIndex ){ 
	    	$("td:eq(5)",nRow).html("<i class='fa fa-angle-double-down' aria-hidden='true'></i>")
	    	$("td:eq(5)",nRow).off("click").on("click",function(){
	    		if($(this).parent("tr").next('.detail-control').length==0){
	    			$(this).parent("tr").after("<tr class='detail-control' ><td colspan='6' >" +
	    					"<table class='table table-hover' id='saleLineItemTable'>" +
	    					"<caption>订单明细</caption>"+
	    					"<thead>" +
	    					"<tr>" +
	    					"<th>商品名称</th><th>商品编码</th><th>商品类型</th><th>规格</th><th>数量</th><th>描述</th>" +
	    					"</tr>" +
	    					"</thead>" +
	    					"<tbody></tbody>"+
	    					"</table>" +
	    					"</td></tr>")
	    			$(this).children('i').attr("class","fa fa-angle-double-up")
	    			$(this).parent("tr").siblings("tr").next('.detail-control').remove()
	    			$(this).parent("tr").siblings("tr").find('i').attr("class","fa fa-angle-double-down")
	    			detailControl($("td:eq(0)",nRow).html(),$(this).parent("tr").next())
	    		}
	    		else{
	    			$(this).parent("tr").next('.detail-control').remove()
	    			$(this).children('i').attr("class","fa fa-angle-double-down")
	    		}
	    	})
		},
		"fnRowCallback": function(nRow, aaData, iDisplayIndex, iDisplayIndexFull) {
			$("td:eq(5)",nRow).find('i').attr("class","fa fa-angle-double-down")
		},
	})
	function detailControl(a,tr){
		$.ajax({
			url: "getItem.action",
			type:"post",
			dataType:"json",
			data:{
				"saleOrder.saleOrderNo":a
			},
			success:function(result){
//				console.log(result)
				saleLineItemTable(result,tr)
			},
			error:function(){
				
			}
		})
	}
}
function saleLineItemTable(data,tr){
	$('#saleLineItemTable').DataTable({
		destroy: true,
		"bAutoWidth":false,
		responsive: true,
		"bFilter": false,//搜索栏
//		"bStateSave": true,
		"aLengthMenu": [[3, 5, 7, -1], [3, 5, 7, "全部"]],
		data: data,
		//使用对象数组，一定要配置columns，告诉 DataTables 每列对应的属性
		columns: [{
				data: 'product.productName'
			},
			{
				data: 'product.productNo'
			},
			{
				data: 'product.producttype.name'
			},
			{
				data: 'saleItem.spec'
			},
			{
				data: 'saleItem.quantity'
			},
			{
				data: 'product.remark'
			}
		],
		language: {
	        "sProcessing": "处理中...",
	        "sLengthMenu": "显示 _MENU_ 项结果",
	        "sZeroRecords": "没有匹配结果",
	        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
	        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
	        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
	        "sInfoPostFix": "",
	        "sSearch": "搜索:",
	        "sUrl": "",
	        "sEmptyTable": "表中数据为空",
	        "sLoadingRecords": "载入中...",
	        "sInfoThousands": ",",
	        "oPaginate": {
	            "sFirst": "首页",
	            "sPrevious": "上页",
	            "sNext": "下页",
	            "sLast": "末页"
	        },
	        "oAria": {
	            "sSortAscending": ": 以升序排列此列",
	            "sSortDescending": ": 以降序排列此列"
	        }
	    },
	    "fnCreatedRow": function( nRow, aData, iDataIndex ){ 
	    	
		},
		"fnRowCallback": function(nRow, aaData, iDisplayIndex, iDisplayIndexFull) {

		},
	})
}
function paymentDecision(a,array){
	var queen = Number($("#queenNo").text())
	$('.payment-footer button').off("click").on("click",function(){
		var d = {
				"saleOrder.saleOrderNo":a,
				"payment.amount":$('.footer-btn li').eq(2).find("i").eq(1).text(),
				"payment.payType":$(this).text(),
				"staff.staffNo":"2"
			}
			console.log(d)
			if($("input[name='payment']:checked").val()=="现金"){
				
			}
		if($("#cash").val()!=""){
			if($('#printTable').children("tfoot").find("td").eq(4).find("span").eq(2).html()>=0){
				$.ajax({
					url: "addPayment.action",
					type:"post",
					dataType:"json",
					data:{
						"saleOrder.saleOrderNo":a,
						"payment.amount":$('.footer-btn li').eq(2).find("i").eq(1).text(),
						"payment.payType":$("input[name='payment']:checked").val(),
						"staff.staffNo":"2"
					},
					success:function(result){
						$('.product-list ul li').remove()
						minusRedDotsTips(name,"all",0)
						productModule.TotalProduct()
						$("#queenNo").text(queen+1)
						$('.close').click()
						alert("成功")
						preview()
					},
					error:function(){
						
					}
				})
			}
			else{
				alert("应付现金太少")
			}
		}
		else{
			alert("请填入实付金额")
		}
	})
}
function receipt(){
	var myDate = new Date();
	var mytime=myDate.toLocaleString( );
	var array= $('.product-list ul li').map(function(){
		return {
			"name":$(this).find("h4").text(),
			"itemId":$(this).attr("prono"),
			"quantity":$(this).find('.product-num').val(),
			"price":$(this).find(".product-num-price").children().text(),
			"spec":$(this).find('.product-middle-spec').text(),
			"sweetness":$('.swt').val(),
			"temperature":$('.tmp').val()
		}
	})
	$('#printTable tbody').html("")
	for(var i=0;i<array.length;i++){
		var tr = "<tr><td>"+array[i].name+"</td><td>"+array[i].price+"</td><td>/</td><td>"+array[i].price+"</td><td>"+array[i].quantity+"</td><td>"+array[i].price*array[i].quantity+"</td></tr>"
		$('#printTable').children("tbody").append(tr)
	}
	$("#dutyStaff").html($('.onDuty').text())
	$("#printDate").html(mytime)
	var cash = $('.order-total-foot li').eq(1).find("span").text()
	$('#printTable').children("tfoot").find("td").eq(4).find("span").eq(0).html(cash)
	$("#queenNumber").html($('.order-total-foot li').eq(2).find("span").text())
	$('#printTable').children("tfoot").find("td").eq(4).find("span").eq(1).html(cash)
	$('#printTable').children("tfoot").find("td").eq(4).find("span").eq(2).html(0)
}
function cash(a){
	$('#cash').show()
	$("#cash").val("")
	$('.payment-footer').find("input[type='radio']").change(function(){
		if($(this).val()!="现金"){
			$("#cash").val($('#printTable').children("tfoot").find("td").eq(4).find("span").eq(0).html())
			$("#cash").hide()
		}
		else{
			$("#cash").val("")
		}
	})
}
function takeCash(a){
	var t = $('#printTable').children("tfoot").find("td").eq(4).find("span").eq(0).html()
	var cash = $("#cash").val()
	$('#printTable').children("tfoot").find("td").eq(4).find("span").eq(1).html(cash)
	$('#printTable').children("tfoot").find("td").eq(4).find("span").eq(2).html(cash-t)
}
function preview()    
{   
   bdhtml=window.document.body.innerHTML;    
   sprnstr="<!--startprint-->";    
   eprnstr="<!--endprint-->";    
   prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+17);    
   prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));    
//   window.document.body.innerHTML=prnhtml;
   /*console.log(prnhtml)*/
   myWindow=window.open()
   myWindow.document.body.innerHTML=prnhtml; 
   window.print();    
}  